package com.ktjy.filter;

import com.ktjy.entity.SysRight;
import com.ktjy.entity.SysUser;
import com.ktjy.service.ISysRightService;
import com.ktjy.utils.RedisUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

@Component
public class FormAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtils redisUtils;



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader("Token");
        if (redisUtils.get(token) != null) {
            SysUser user = (SysUser) redisUtils.get(token);



            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsrName(),
                    new BCryptPasswordEncoder().encode(user.getUsrPassword()),
                    AuthorityUtils.createAuthorityList(user.getRightList())
            ); // 使用空密码和空权限列表，因为我们只验证token的有效性。实际项目中应加载用户权限。
            SecurityContextHolder.getContext().setAuthentication(auth); // 设置认证信息到上下文中。这样其他组件可以访问认证信息。
        }
        filterChain.doFilter(request, response);

    }
}
